package com.lijin.download;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;

import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class DownLoadUtls {

    public static void down(String downUrl,String saveDirPath,DownBean bean){
        System.err.println("当前下载的文件地址为："+downUrl+"，本任务一共需要下载的文件数量为："+bean.getUrls().size());
        if(StringUtils.isBlank(downUrl)){ return; }
        String saveName = FilenameUtils.getName(downUrl);
        //格式化文件名称
        Matcher matcher = Pattern.compile("\\d+").matcher(saveName);
        if(matcher.find()){
            String match = matcher.group();
            saveName = saveName.replace(match, String.format("%04d", Integer.parseInt(match)));
        }
        bean.getMergeNames().add(saveName);
        try {
            ByteArrayOutputStream stream = HttpClientUtils.getRequest(downUrl);
            Path target = Paths.get(saveDirPath, saveName);
            Files.write(target,stream.toByteArray(), StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING);
        } catch (Exception e) {
            throw new RuntimeException("下载m3u8内容文件异常："+downUrl,e);
        }
    }
}
